package com.wss.lsl.alading.controller.cardimage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wss.lsl.alading.domain.FileItem;
import com.wss.lsl.alading.service.IFileItemService;

@Controller
@RequestMapping("/cardimage")
public class CardimageController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private IFileItemService fileItemService;

	@RequestMapping("/show")
	public String show(Integer id, Model model) {

		return "cardImage/addCardImage";
	}

	@RequestMapping("/create")
	@ResponseBody
	public String create(@RequestParam("description") String description,
			@RequestParam("pic") MultipartFile file,
			HttpServletResponse response) {

		// response.setContentType("");

		String contentType = file.getContentType();
		String originalFileName = file.getOriginalFilename();
		logger.info("addImage contentType={}, originalFileName={}",
				new Object[] { contentType, originalFileName });
		int type = 3; // 保存成功
		try {
			byte[] bbuf = file.getBytes();
			if (bbuf != null && bbuf.length > 0) {
				FileItem fileItem = new FileItem();
				fileItem.setContent(bbuf);
				fileItem.setMimeType(contentType);
				fileItem.setOriginalFilename(originalFileName);
				fileItem.setFilesize(bbuf.length);
				fileItem.setDescription(description);
				fileItemService.save(fileItem);
			} else {
				type = 4;
			}
			// 避免ajax 提交form表单出现文件下载框
			// response.setContentType("text/html; charset=UTF-8");
			// response.getWriter().write("{\"type\":" + type + "}");
			// response.getWriter().flush();
			// response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
			type = 4; // 保存失败
		}

		return "{\"type\":" + type + "}";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(@ModelAttribute FileItem fileItem,
			Integer page, Integer rows, Model model) {

		page = (page == null) ? 1 : page;
		rows = (rows == null) ? 10 : rows;

		List<FileItem> list = fileItemService.searchFileItems(page, rows,
				fileItem);
		Integer count = fileItemService.countFileItems(page, rows, fileItem);
		logger.info("images list count: " + count);

		Map<String, Object> respond = new HashMap<String, Object>();
		respond.put("rows", (null == list) ? new ArrayList<FileItem>() : list);
		respond.put("page", page);
		respond.put("total", (null == count) ? 0 : count);

		return respond;
	}

	@RequestMapping("/listCardImage")
	public String list() {

		return "cardImage/listCardImage";
	}

	@RequestMapping("/delete/{id}")
	@ResponseBody
	public String delete(@PathVariable(value = "id") Integer id) {

		int type = 3; // 删除成功
		try {
			fileItemService.deleteFileItemById(id);
		} catch (Exception e) {
			type = 4;
		}

		return "{\"type\":" + type + "}";
	}

	@RequestMapping("/show/{id}")
	public void show(@PathVariable("id") Integer id,
			HttpServletResponse response) {

		FileItem image = fileItemService.findFileItemById(id);

		response.setContentType(image.getMimeType());
		try {
			response.getOutputStream().write(image.getContent());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
		}
	}

	@RequestMapping("/update/{id}")
	public String update(@PathVariable("id") Integer id, Model model) {

		model.addAttribute("image", fileItemService.findFileItemById(id));
		return "cardImage/updateCardImage";
	}

	@RequestMapping("/update")
	@ResponseBody
	public String update(@ModelAttribute FileItem fileItem,
			@RequestParam("pic") MultipartFile file) {

		int type = 3; // 保存卡图片成功

		try {
			String contentType = file.getContentType();
			String originalFileName = file.getOriginalFilename();
			logger.info("updateImage contentType={}, originalFileName={}",
					new Object[] { contentType, originalFileName });
			byte[] bbuf = file.getBytes();

			if (bbuf != null && bbuf.length > 0) {// 没有上传图片，则只更新图片描述
				fileItem.setContent(bbuf);
				fileItem.setFilesize(bbuf.length);
				fileItem.setMimeType(contentType);
				fileItem.setOriginalFilename(originalFileName);
			}
			fileItemService.updateDescContent(fileItem);
		} catch (Exception e) {
			e.printStackTrace();
			type = 4; // 保存卡图片失败
		}

		return "{\"type\":" + type + "}";
	}

	@RequestMapping(value = "/something")
	@ResponseBody
	public String helloWorld() {
		return "Hello World";
	}
}
